package org.example.servicefaculty.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.model.manage.bean.po.Counselor;
import org.example.model.manage.bean.po.Faculty;
import org.example.model.manage.bean.po.Major;
import org.example.model.manage.bean.po.Student;
import org.example.model.manage.bean.vo.FacultyCount;
import org.example.model.manage.bean.vo.MajorCount;
import org.example.servicefaculty.mapper.FacultyMapper;
import org.example.servicefaculty.service.FacultyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  学院服务实现类 - 学院只能管理自己学院内的专业、辅导员、学生
 * </p>
 *
 * @author author
 * @since 2025-08-14
 */
@Service
public class FacultyServiceImpl extends ServiceImpl<FacultyMapper, Faculty> implements FacultyService {

    @Autowired
    private FacultyMapper facultyMapper;

    // ========== 学院信息管理（只读） ==========

    @Override
    public Faculty getFacultyById(Integer facultyId) {
        return getById(facultyId);
    }

    // ========== 专业管理（学院内） ==========

    @Override
    public List<Major> getMajorsByFacultyId(Integer facultyId) {
        return facultyMapper.selectMajorsByFacultyId(facultyId);
    }

    // ========== 辅导员管理（学院内） ==========

    @Override
    public List<Counselor> getCounselorsByFacultyId(Integer facultyId) {
        // 先获取学院信息
        Faculty faculty = getFacultyById(facultyId);
        if (faculty == null) {
            return new ArrayList<>();
        }
        
        // 使用学院名称查询辅导员，因为Counselor实体只有faculty字段（学院名称）
        return facultyMapper.selectCounselorsByFacultyName(faculty.getFaculty());
    }

    @Override
    public Counselor getCounselorById(Integer id, Integer facultyId) {
        // 先获取辅导员信息
        Counselor counselor = facultyMapper.selectCounselorById(id);
        if (counselor == null) {
            return null;
        }
        
        // 获取学院信息，验证辅导员是否属于该学院
        Faculty faculty = getFacultyById(facultyId);
        if (faculty == null) {
            return null;
        }
        
        // 比较学院名称而不是学院ID，因为Counselor实体只有faculty字段（学院名称）
        if (counselor.getFaculty().equals(faculty.getFaculty())) {
            return counselor;
        }
        
        return null;
    }

    // ========== 学生管理（学院内） ==========

    @Override
    public List<Student> getStudentsByMajorId(Integer majorId, Integer facultyId) {
        // 验证专业是否属于该学院
        Major major = facultyMapper.selectMajorById(majorId);
        if (major == null || !major.getFacultyId().equals(facultyId)) {
            return new ArrayList<>();
        }
        
        return facultyMapper.selectStudentsByMajorId(majorId);
    }

    @Override
    public Student addStudent(Student student, Integer facultyId) {
        // 验证专业是否属于该学院
        Major major = facultyMapper.selectMajorById(student.getMajorId());
        if (major == null || !major.getFacultyId().equals(facultyId)) {
            throw new IllegalArgumentException("专业不存在或无权限添加学生");
        }
        
        // 验证学生是否已存在
        Student existing = facultyMapper.selectStudentByNameAndMajorId(student.getName(), student.getMajorId());
        if (existing != null) {
            throw new IllegalArgumentException("学生 " + student.getName() + " 在该专业中已存在");
        }
        
        facultyMapper.insertStudent(student);
        return student;
    }

    @Override
    public Student updateStudent(Student student, Integer facultyId) {
        // 验证学生是否属于该学院
        Student existing = facultyMapper.selectStudentByNameAndMajorId(student.getName(), student.getMajorId());
        if (existing == null) {
            throw new IllegalArgumentException("学生不存在");
        }
        
        Major major = facultyMapper.selectMajorById(student.getMajorId());
        if (major == null || !major.getFacultyId().equals(facultyId)) {
            throw new IllegalArgumentException("无权限修改该学生信息");
        }
        
        facultyMapper.updateStudent(student);
        return student;
    }

    @Override
    public boolean deleteStudent(Integer studentId, Integer facultyId) {
        // 验证学生是否属于该学院
        Student student = facultyMapper.selectStudentsByMajorId(studentId).stream()
                .filter(s -> s.getId().equals(studentId))
                .findFirst()
                .orElse(null);
        
        if (student == null) {
            return false;
        }
        
        Major major = facultyMapper.selectMajorById(student.getMajorId());
        if (major == null || !major.getFacultyId().equals(facultyId)) {
            return false;
        }
        
        return facultyMapper.deleteStudent(studentId) > 0;
    }

    // ========== 统计功能 ==========

    @Override
    public FacultyCount getFacultyCount(Integer facultyId) {
        FacultyCount facultyCount = facultyMapper.selectFacultyCount(facultyId);
        if (facultyCount != null) {
            Integer totalStudents = facultyCount.getTotalStudents();
            Integer reportedStudents = facultyCount.getReportedStudents();
            
            if (totalStudents != null && totalStudents > 0) {
                Double reportRate = (double) reportedStudents / totalStudents;
                facultyCount.setReportRate(reportRate);
            } else {
                facultyCount.setReportRate(0.0);
            }
            
            facultyCount.setReportNum(reportedStudents);
            facultyCount.setUnreportNum(totalStudents - reportedStudents);
            facultyCount.setReportedStudents(null);
        }
        return facultyCount;
    }

    @Override
    public List<MajorCount> getMajorCountsByFacultyId(Integer facultyId) {
        List<MajorCount> majorCounts = facultyMapper.selectMajorCountsByFacultyId(facultyId);
        
        for (MajorCount majorCount : majorCounts) {
            Integer totalStudents = majorCount.getTotalStudents();
            Integer reportedStudents = majorCount.getReportedStudents();
            
            if (totalStudents != null && totalStudents > 0) {
                Double reportRate = (double) reportedStudents / totalStudents;
                majorCount.setReportRate(reportRate);
            } else {
                majorCount.setReportRate(0.0);
            }
            
            majorCount.setReportNum(reportedStudents);
            majorCount.setUnReportNum(totalStudents - reportedStudents);
            majorCount.setTotalStudents(null);
            majorCount.setReportedStudents(null);
        }
        
        return majorCounts;
    }
}